package com.bangyu.monitor.modular.system.biz;

import com.bangyu.monitor.core.cache.BridgeCache;
import com.bangyu.monitor.core.common.constant.Const;
import com.bangyu.monitor.core.common.constant.ConstantEnum;
import com.bangyu.monitor.core.util.FormatUtil;
import com.bangyu.monitor.core.util.ReportTemplateRegisterUtil;
import com.bangyu.monitor.modular.system.entity.*;
import com.bangyu.monitor.modular.system.service.BridgeService;
import com.bangyu.monitor.modular.system.service.PayloadService;
import com.bangyu.monitor.modular.system.service.RiskService;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.images.ByteArrayImageProvider;
import fr.opensagres.xdocreport.document.images.ClassPathImageProvider;
import fr.opensagres.xdocreport.document.images.IImageProvider;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * @Auther: zhangxue
 * @Date: 19/5/27 20:26
 * @Description:
 */
@Service
@Slf4j
public class FileDownloadBiz {

    @Autowired
    private PayloadService payloadService;

    @Autowired
    private BridgeService bridgeService;

    @Autowired
    private RiskService riskService;

    @Autowired
    private DataViewBiz dataViewBiz;

    public  File  reportDownload(String beamNo,String startDate,String endDate,String img64Url){
        try
        {

            Date now = new Date();
            String time = String.valueOf(now.getTime());
            IXDocReport report = ReportTemplateRegisterUtil.INSTANCE.getTemplate();
            FieldsMetadata metadata = report.createFieldsMetadata();
            metadata.addFieldAsImage( "stand_bend_trend" );

            IContext context = report.createContext();

            IImageProvider imgProvider = new ByteArrayImageProvider(decodeBase64(img64Url));
            context.put( "stand_bend_trend", imgProvider );

            Integer startDateInt = FormatUtil.parseDateStr2Int(startDate);
            Integer endDateInt = FormatUtil.parseDateStr2Int(endDate);

            MonitorInfoSummary summary =dataViewBiz.monitorInfoSummary(startDateInt,endDateInt);
            summary.setStartTime(startDate);
            summary.setEndTime(endDate);
            context.put("monitorSummary",summary);
            context.put( "monitorDetail", getMonitorInfoDetail(beamNo,startDateInt,endDateInt));

            File reportDoc =new File( String.format("report/%s-%s.docx",beamNo,time) );
            OutputStream out = new FileOutputStream( reportDoc );
            report.process( context, out );
            return reportDoc;

        }
        catch ( Exception e )
        {
            log.error("download word report error",e);
            return null;
        }

    }

    public MonitorInfoDetail getMonitorInfoDetail(String beamNo,Integer startDateInt,Integer endDateInt){
        MonitorInfoDetail detail = new MonitorInfoDetail();

        //重型荷载次数和轻型荷载数量
        List<PayloadCount> payloadCounts = payloadService.queryCountByPayloadType(beamNo,startDateInt,endDateInt);
        payloadCounts.forEach(c -> {
            if(Const.PAYLOAD_TYPE_LIGHT == c.getPayloadType()){
                detail.setLightCount(c.getCount());
            }else {
                detail.setHeavyCount(c.getCount());
            }
        });
        detail.cacuPayloadRate();

        Bridge bridge = bridgeService.getByBeamNo(beamNo);
        if(bridge != null){
            detail.setCustomerName(bridge.getManagerOrg());
            detail.setBridgeName(bridge.getBridgeName());
            detail.setLine(bridge.getLine());
            detail.setSpan(bridge.getSpan());
            detail.setStakeCode(bridge.getStakeCode());

            if(bridge.getTypeOne() != null){
                detail.setProperty(ConstantEnum.BridgeProperty.getName(bridge.getTypeOne()));
            }
            detail.setSpan(bridge.getSpan());
            detail.setThreshold(bridge.getThreshold());
        }

        List<RiskCount> riskCounts = riskService.riskCountByLevelAndType(beamNo,startDateInt,endDateInt);
        if(CollectionUtils.isNotEmpty(riskCounts)){
            riskCounts.forEach(r ->{
                Integer riskType = r.getRiskType();
                Integer riskLevel = r.getRiskLevel();
                if(riskLevel == ConstantEnum.RiskLevel.RISK_LEVEL_WARN.getKey()){
                    if(riskType == ConstantEnum.RiskType.RISK_TYPE_NDJX.getRiskCode()){
                        detail.setExtremityWarnCount(r.getCount());
                    } else if(riskType == ConstantEnum.RiskType.RISK_TYPE_TFHZ.getRiskCode()){
                        detail.setEmergencyWarnCount(r.getCount());
                    }
                }else if(riskLevel == ConstantEnum.RiskLevel.RISK_LEVEL_ALARM.getKey()){
                    if(riskType == ConstantEnum.RiskType.RISK_TYPE_NDJX.getRiskCode()){
                        detail.setExtremityAlarmCount(r.getCount());
                    } else if(riskType == ConstantEnum.RiskType.RISK_TYPE_TFHZ.getRiskCode()){
                        detail.setEmergencyAlarmCount(r.getCount());
                    }
                }

            });
        }
        return detail;

    }

    private byte[] decodeBase64(String base64Info){
        if(StringUtils.isEmpty(base64Info)){
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        String[] arr = base64Info.split("base64,");
        // 数据中： ...  在"base64,"之后的才是图片信息
        try {
            return decoder.decodeBuffer(arr[1]);
        } catch (Exception e) {
            log.error("解析图片出错",e);
        }

        return null;
    }

}
